package com.e3.core.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class InetUtils {

	private static Map<String, String> hostNames = new ConcurrentHashMap<String, String>();
	private static Map<String, Boolean> isIPV6 = new ConcurrentHashMap<String, Boolean>();
	private static String localHostName = "localhost";
	static{
		try {
			localHostName = InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
			localHostName = "localhost";
			e.printStackTrace();
		}
	}
	
	public static boolean isIpV6Address(String address){
		try {
			if(isIPV6.get(address) == null){
				InetAddress iaddress = InetAddress.getByName(address);
				if(iaddress.getAddress().length==16){
					isIPV6.put(address, true);
					return true;
				}else{
					isIPV6.put(address, false);
				}
			}else
				return isIPV6.get(address);
		} catch (UnknownHostException e) {
			return false;
		}
		return false;
	}
	
	public static String getHostNameByAddress(String address){
		try {
			String hostName = hostNames.get(address);
			if(hostName == null){
				InetAddress iaddress = InetAddress.getByName(address);
				hostName = iaddress.getHostName();
				hostNames.put(address, hostName);
			}
			if("localhost".equals(hostName)){
				return localHostName;
			}
			return hostName;
		} catch (UnknownHostException e) {}
		return address;
	}
	
	public static String getLocalHostName(){
		return localHostName;
	}
	
	public static boolean isLocalHost(String address,boolean hasPort){
		if(hasPort){
			address = address.substring(0,address.lastIndexOf(":"));
		}
		String hostName = getHostNameByAddress(address);
		String localHostName = getLocalHostName();
		if(localHostName.equals(hostName)){
			return true;
		}
		return false;
	}
	
	public static void main(String[] args){
		//System.out.println(InetUtils.isLocalHost("127.0.0.1:1099",true));
		//System.out.println(InetUtils.getHostNameByAddress("fe80:0:0:0:2c0:9fff:fe34:8f5a%2"));
		//System.out.println(System.getProperty("user.timezone"));
		//System.out.println(new java.util.Date().toString());

	}
}
